package com.jww.cloud.auth.config.error;

import com.alibaba.fastjson.JSON;
import com.jww.common.core.constant.enums.ResultCodeEnum;
import com.jww.common.web.model.dto.Result;
import com.jww.common.web.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class JwwOAuth2AuthenticationEntryPoint extends OAuth2AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        log.debug("JbaOAuth2AuthenticationEntryPoint -> commence...");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setStatus(ResultCodeEnum.UNAUTHORIZED.value());
        Result result = ResultUtil.fail(ResultCodeEnum.UNAUTHORIZED, authException.getMessage());
        response.getWriter().append(JSON.toJSONString(result));
    }
}
